package com.swz.dcrm.ui.mine;


import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;

import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;

import android.os.Environment;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.model.IPickerViewData;


import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.makeramen.roundedimageview.RoundedImageView;
import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import com.swz.dcrm.BuildConfig;
import com.swz.dcrm.R;
import com.swz.dcrm.model.AddressBean;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.PersonalInfo;
import com.swz.dcrm.model.PersonalInfoUpdateVo;
import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.ui.viewmodel.MainViewModel;
import com.swz.dcrm.ui.viewmodel.StaffViewModel;
import com.swz.dcrm.util.Constant;
import com.swz.dcrm.util.PermissionUtil;
import com.xh.baselibrary.widget.CircleImageView;
import com.yalantis.ucrop.UCrop;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;


import org.w3c.dom.Text;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * A simple {@link Fragment} subclass.
 */
public class InformationFragment extends BaseFragment implements Validator.ValidationListener {

    @BindView(R.id.toolbar_title)
    TextView title;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.iv_headPic)
    RoundedImageView ivHeadPic;

    @NotEmpty(messageResId = R.string.not_be_null_name)
    @BindView(R.id.tv_name)
    TextView tvName;
    @NotEmpty(messageResId = R.string.not_be_null_phone)
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_post)
    TextView tvPost;
    @BindView(R.id.tv_area)
    TextView tvArea;
    @Inject
    MainViewModel mainViewModel;
    @Inject
    StaffViewModel staffViewModel;


    private Uri uriTempFile;

    private OptionsPickerView optionsPickerView;
    private ArrayList<AddressBean> addressBeans;
    private ArrayList<String> options1Items = new  ArrayList<>();
    private ArrayList<ArrayList<String> >options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    PersonalInfoUpdateVo personalInfoUpdateVo=new PersonalInfoUpdateVo();
    private PersonalInfo personalInfo;
    Validator validator;

    public InformationFragment() {
        // Required empty public constructor
    }


    @Override
    public void onLoadRetry() {

        mainViewModel.getPersonalInfo().observe(this, personalInfoBaseResponse -> {
            if (personalInfoBaseResponse.isSuccess()) {
                personalInfo=personalInfoBaseResponse.getData();
                tvName.setText(personalInfoBaseResponse.getData().getName());
                tvPhone.setText(personalInfoBaseResponse.getData().getPhone());
                tvArea.setText(personalInfoBaseResponse.getData().getArea());
                tvPost.setText(personalInfoBaseResponse.getData().getRole().getRoleGroup());
                Glide.with(getActivity())
                        .load(personalInfoBaseResponse.getData().getHeadPortraitUrl())
                        .into(ivHeadPic);
            }
        });
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    public int layoutId() {
        return R.layout.fragment_infomation;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);

         validator = new Validator(this);
        validator.setValidationListener(this);

        optionsPickerView=new OptionsPickerView.Builder(getActivity(), (options1, options2, options3, v) -> {
            if(options1Items.get(options1).equals(options2Items.get(options1).get(options2))){
                tvArea.setText(options2Items.get(options1).get(options2)
                        +options3Items.get(options1).get(options2).get(options3));
            }else {
                tvArea.setText(options1Items.get(options1)+options2Items.get(options1).get(options2)
                        +options3Items.get(options1).get(options2).get(options3));
            }
        }).setCancelText("取消")
                .setSubmitText("确定")
                .setTextColorCenter(getResources().getColor(R.color.black_2f3234))
                .setSubmitColor(getResources().getColor(R.color.black_2f3234))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.black_2f3234)).build();//取消按钮文字颜色build();
        Gson gson = new Gson();
        addressBeans = gson.fromJson(getCityJson(), new TypeToken<List<AddressBean>>() {
        }.getType());

        parseData();
        optionsPickerView.setPicker(options1Items,options2Items,options3Items);;
        title.setText(getString(R.string.information_title));
        tvRight.setText(getString(R.string.information_save));
        mainViewModel.getEdit().observe(this,edit -> {
            if(edit==null){
                return;
            }
            if(edit.getTitle().equals(getString(R.string.information_name))){
                tvName.setText(edit.getValue());
            }else if(edit.getTitle().equals(getString(R.string.information_phone))){
                tvPhone.setText(edit.getValue());
            }
        });

        onLoadRetry();
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUEST_CODE_GALLERY && resultCode == Activity.RESULT_OK) {
          List<Uri>  mSelected = Matisse.obtainResult(data);
          if(mSelected!=null&&mSelected.size()>0){
              uriTempFile = Uri.parse("file:///"   +getActivity().getExternalFilesDir(null) +File.separator + "temp.jpg");
              UCrop.of(mSelected.get(0), uriTempFile)
                      .withAspectRatio(1, 1)
                      .start(getContext(),this);
          }
        }else if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
            final Uri resultUri = UCrop.getOutput(data);

            mainViewModel.upload(new File(resultUri.getPath()))
                    .observe(this, stringBaseResponse -> {

                        personalInfoUpdateVo.setHeadPortraitUrl(stringBaseResponse.getData());
                        Glide.with(getActivity())
                                .load(stringBaseResponse.getData())
                                .into(ivHeadPic);
                    });
        } else if (resultCode == UCrop.RESULT_ERROR) {

        }
    }

    @OnClick(R.id.c_headPic)
    public void headPic() {
        if(!PermissionUtil.needCarmaAndSdCard(this)){
            Matisse.from(this)
                    .choose(MimeType.ofAll())
                    .countable(true)
                    .capture(true)
                    .captureStrategy(new CaptureStrategy(true, BuildConfig.APPLICATION_ID +".file.provider"))
                    .maxSelectable(1)
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                    .thumbnailScale(0.85f)
                    .imageEngine(new GlideEngine())
                    .showPreview(false) // Default is `true`
                    .theme(R.style.CustomMatisseStyle)
                    .forResult(Constant.REQUEST_CODE_GALLERY);
        }

    }

    @OnClick(R.id.ll_area)
    public void area() {
        optionsPickerView.show();
    }

    @OnClick({R.id.ll_name, R.id.ll_phone})
    public void edit(View view) {
        EditInfoFragmentArgs.Builder builder = new EditInfoFragmentArgs.Builder();
        builder.setInputType(String.valueOf(InputType.TYPE_CLASS_NUMBER));
        switch (view.getId()) {
            case R.id.ll_name:
                builder.setTitle(getString(R.string.information_name))
                        .setValue(tvName.getText().toString());
                break;
            case R.id.ll_phone:
                builder.setTitle(getString(R.string.information_phone))
                        .setValue(tvPhone.getText().toString());
                break;
        }
        go(null, R.id.action_infomationFragment_to_editInfoFragment, builder.build().toBundle());
    }
    private String getCityJson() {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = getActivity().getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open("region.json")));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }


    private void parseData(){

//     把解析后的数据组装成想要的list
        for(AddressBean addressBean:addressBeans){
            options1Items.add(addressBean.getLabel());
        }

//     遍历省
        for(int i = 0; i <addressBeans.size() ; i++) {
//         存放城市
            ArrayList<String> cityList = new ArrayList<>();
//         存放区
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();
//         遍历市
            for(int c = 0; c <addressBeans.get(i).getChildren().size() ; c++) {
//        拿到城市名称
                String cityName = addressBeans.get(i).getChildren().get(c).getLabel();
                cityList.add(cityName);

                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表
                if (addressBeans.get(i).getChildren().get(c).getChildren() == null || addressBeans.get(i).getChildren().get(c).getChildren().size() == 0) {
                    city_AreaList.add("");
                } else {
                    List<String>list=new ArrayList<>();
                    for(AddressBean.CityBean.AreaBean areaBean:addressBeans.get(i).getChildren().get(c).getChildren()){
                        list.add(areaBean.getLabel());
                    }
                    city_AreaList.addAll(list);
                }
                province_AreaList.add(city_AreaList);
            }
            /**
             * 添加城市数据
             */
            options2Items.add(cityList);
            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
        }

    }

    @OnClick(R.id.iv_back)
    public void backClick() {
        NavHostFragment.findNavController(this).navigateUp();
    }

    @OnClick(R.id.tv_right)
    public void save(){
        validator.validate();
    }

    @Override
    public void onValidationSucceeded() {
        String name=tvName.getText().toString();
        String phone=tvPhone.getText().toString() ;
        String area= tvArea.getText().toString();
        personalInfoUpdateVo.setId(personalInfo.getId());
        personalInfoUpdateVo.setArea(area);
        personalInfoUpdateVo.setPhone(phone);
        personalInfoUpdateVo.setName(name);
        personalInfoUpdateVo.setId(personalInfo.getId());



        staffViewModel.saveStaff(personalInfoUpdateVo)
                .observe(this, personalInfoBaseResponse -> {

                    if(personalInfoBaseResponse.isSuccess()&&personalInfoUpdateVo.getHeadPortraitUrl()!=null){
                        mainViewModel.getHeadPic().setValue(personalInfoUpdateVo.getHeadPortraitUrl());
                    }
                    showToast(personalInfoBaseResponse.getMsg());
                    if(personalInfoBaseResponse.isSuccess()){
                        backClick();
                    }

                });
    }

    @Override
    public void onValidationFailed(List<ValidationError> errors) {
        for (ValidationError error : errors) {

            String message = error.getCollatedErrorMessage(getContext());

            showToast(message);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_WRITE_EXTERNAL_STORAGE_CAMERA:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                   headPic();
                }
                break;
        }
    }

    @Override
    public void onDestroyView() {
        mainViewModel.getEdit().setValue(null);
        super.onDestroyView();
    }
}
